<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: huajie <banhuajie@163.com>
// +----------------------------------------------------------------------

namespace Admin\Controller;

/**
 * 行为控制器
 * @author huajie <banhuajie@163.com>
 */

class CapitalController extends AdminController {

    protected  function export($map   = array()){
        $model = M('Loan');
        $volist = $model->where($map)->limit(200)->select();
        $body = array();
        $i=1;
        $LOAN_STATUS = C('LOAN_STATUS');
        foreach($volist as $val){
            $i++;
            $rows = [
                'A'=>"'".$val['id'],
                'B'=>$val['uid'],
                'C'=>$val['name'],
                'D'=>$val['money'],
                'E'=>$val['payable'],
                'F'=>$val['repayment'],
                'G'=>$val['day'],
                'H'=>$val['create_time']?date('Y-m-d H:i:s',$val['create_time']):'',
                'I'=>$val['loan_time']?date('Y-m-d H:i:s',$val['loan_time']):'',
                'J'=>$val['huankuan_time']?date('Y-m-d H:i:s',$val['huankuan_time']):'',
                'K'=>$LOAN_STATUS[$val['status']],
            ];
            $body[$i]=$rows;
        }

        $data = [
            'header'=>['A1'=>'合同ID','B1'=>'用户UID','C1'=>'名字','D1'=>'借款金额','E1'=>'放款金额','F1'=>'还款金额','G1'=>'借款天数','H1'=>'申请时间','I1'=>'放款时间','J1'=>'还款时间','K1'=>'状态'],
            'body'=> $body,
        ];

        Excel($data);
    }


  







    public function index(){


       // exit;
        //生成
        $type       = I('get.type');
        $title       = I('get.title');
        $status     = I('get.status','');
        $name       = I('get.name','');
        $timestart  = I('get.time-start','');
        $timeend    = I('get.time-end','');
        $export     = I('get.export',false);

        $map =array();
        $order='create_time desc';

        if(!empty($timestart) && !empty($timeend)){
            $timestart = strtotime($timestart);
            $timeend = strtotime($timeend);
        }
        if(!empty($title)){
            if(is_string($title)){
                if(strlen($title)>=16){
                    if(strlen($title)>=20){
                        $map['pay_num']         = $title;
                    }else{
                        $map['oid_returnbill']         = $title;
                    }
                    
                }else{
                    $map['name']         = array('like',"%{$title}%");
                }
            }else{
                $map['id']         = array('eq',$title);
            }
        }
        if(!empty($name)){
            $map['name']      = array('eq',$name);
        }
        

        if($type==1){ //发款总额
            $map['status']         = array(array('eq',5),array('eq',6), 'or');
            if(!empty($timestart) && !empty($timeend)){
            $map['loan_time']      = array(array('gt',$timestart),array('lt',$timeend), 'or');
            }
        }elseif($type==2){ //已还款总额
            $map['status']      = array('eq',6);
            if(!empty($timestart) && !empty($timeend)){
                $map['huankuan_time']      = array(array('gt',$timestart),array('lt',$timeend), 'or');
            }
        }elseif($type==3){ //待还款总额
            $map['status']      = array('eq',5);
            if(!empty($timestart) && !empty($timeend)){
                $map['expire_time']      = array(array('gt',$timestart),array('lt',$timeend), 'or');
            }
        }elseif($type=='today'){ //今日待还款
            $today = strtotime(date('Y-m-d'));
            $tomorrow=strtotime(date('Y-m-d'))+86400;
            $map['status']      = array('eq',5);
            $map['expire_time']      = array('gt',$tody);
            $map['expire_time']      = array('lt',$tomorrow);
            $order='expire_time desc';

        }elseif($type=='renewal'){ //续期用户



            $map['renewal']      = array('gt',0);
            if(!empty($status)){
            $map['status']      = array('eq',$status);
            }

        }elseif(!empty($status)){
            $map['status']      = array('eq',$status);
            if($status==6){
                $order='huankuan_time desc';
            }
            
        }
           


        if($export == true){
            $this->export($map);exit;
        }
        $list   =   $this->lists('Loan', $map,$order,array('status'=>array('egt',-1)));
        // $list   =   $this->lists('Loan', $map,'create_time desc',array('status'=>array('egt',-1)));


        $money      = M('Loan')->where($map)->sum('money');
        $payable    = M('Loan')->where($map)->sum('payable');
        $repayment  = M('Loan')->where($map)->sum('repayment');
        $vetting1  = M('Loan')->where($map)->sum('vetting1');
        $accrual   = M('Loan')->where($map)->sum('accrual');
        $manag     = M('Loan')->where($map)->sum('manag');
        

        $this->assign('_list', $list);
        $sum = [
            'money'     =>$money,
            'payable'   =>$payable,
            'repayment' =>$repayment,
            'vetting1' =>$vetting1,
            'accrual' =>$accrual,
            'manag' =>$manag,
        ];
        



        // $one=D('Loan')->where("uid=".$list['uid'])->select();
        // $jkcs=count($one);
        // $two=D('Loan')->where(['status'=>6,'uid'=>$list['uid']])->select();
        // $ashk=0;
        // $yq=0;
        // foreach($two as $key=>$val){
        //     $date1=date("Ymd",$val['expir_time']);
        //     $date2=date("Ymd",$val['huankuan_time']);
        //     if(strtotime($date1)>=strtotime(date2)){
        //         $ashk=$ashk+1;
        //     }else{
        //         $yq=$yq+1;
        //     }
        // }
        // $three=D('Loan')->where(['status'=>3,'uid'=>$list['uid']])->select();
        // $btg=count($three);

        // $this->assign('jdcs', $jdcs);
        // $this->assign('ashk', $ashk);
        // $this->assign('yq', $yq);
        // $this->assign('btg', $btg);


        $this->assign('sum', $sum);
        $this->assign('_list', $list);
        $this->meta_title = '借款列表';
        $this->display();
    }


    public function qx_order(){
        if(IS_POST){
            $id=I('post.id');
            if($id==1){
                print_r('订单不存在');die;
            }
            $one=D('Loan')->where('id='.$id)->save(['status'=>-1]);
            if($one==1){
                print_r('订单已取消');die;
            }else{
                print_r('订单取消失败');die;
            }
        }
        
        
    }

     public function view($id){
        $model = D('Loan');
        $map = array();
        $map['status']  = 1;
        $map['id']      = $id;
        $model->UpdateStatus($map,2,'',$_SESSION['onethink_admin']['user_auth']['uid']);   //待审核--->>>审核中

        $info = M('Loan')->where('id='.$id)->find();
        // print_r($info);die;

        if($info['status']==5){  //已打款的状态下，去查询付款结果

            $result=$this->query_payment($info['order_num'],$info['oid_paybill']);
            
            $result=json_decode($result,true);
            // print_r($result);die;
            if($result['result_pay']=='APPLY'){  //返回的结果
                $info['result_pay']=1;

            }else if($result['result_pay']=='CHECK'){
                $info['result_pay']=2;
            }else if($result['result_pay']=='SUCCESS'){
                $info['result_pay']=3;
            }else if($result['result_pay']=='PROCESSING'){
                $info['result_pay']=4;
            }else if($result['result_pay']=='CANCEL'){
                $info['result_pay']=5;
            }else if($result['result_pay']=='FAILURE'){
                $info['result_pay']=6;
            }else if($result['result_pay']=='CLOSED'){
                $info['result_pay']=7;
            }

            // APPLY 付款申请
            // CHECK 复核申请
            // SUCCESS 付款成功
            // PROCESSING 付款处理中
            // CANCEL 付款退款（付款成
            // 功后，有可能发生退款）
            // FAILURE 付款失败
            // CLOSED 付款关闭  result_pay  info_order
        }



        $this->assign('info', $info);


        $volist  = M('LoanLog')->where('loan_id='.$info['id'])->order('id desc')->select();
        foreach ($volist as $key => $v) {
            $one=D('Member')->where('uid='.$v['uid'])->find();
            $v['name']=$one['realname'];
            $volist[$key]=$v;
        }

        // $volist  = M('LoanDefault')->select();
        // print_r($volist);die;




        $this->assign('volist', $volist);
        $lixi_list  = M('LoanYuqi')->where('loan_id='.$info['id'])->order('id desc')->select();
        $this->assign('lixi_list', $lixi_list);
        $BankCard = '';

        if($info['status']>=4){
            $BankCard =  M('BankCard')->where('uid='.$info['uid'])->find();
        }
        $real=D('Realname')->where('uid='.$info['uid'])->find();
        $identityNo=$real['identityNo'];
        // echo $identityNo;die;
        $this->assign('identityNo', $identityNo);
        $this->assign('BankCard', $BankCard);
        $this->meta_title = '详细';
        $this->display();
    }
     public function change(){
       $model = D('Loan');
        if(IS_POST){
            $data=I('post.content');
            foreach ($data as $key => $v){
                 if($v['name']=='content'){
                    $content=$v['value'];
                 }
                 if($v['name']=='payable'){
                    $payable=$v['value'];
                 }
                 if($v['name']=='card_number'){
                    $card_number=$v['value'];
                 }
                 if($v['name']=='name'){
                    $name=$v['value'];
                 }
             } 
            $id         = I('post.id');
            $type       = I('post.type');
            $trl = ['status'=>false,'info'=>'操作失败'];

                if($type=='notpass'){ //不通过
                    $map = array();
                    $map['status']  = 2;
                    $map['id']      = $id;




                    $cancel=strtotime(date("Y-m-d"))+7*86400;//不通过，7天后方可再次借款，存下时间，如需开启此功能，需在weixincapital/loan中开启同样的功能
                    D('Loan')->where('id='.$id)->save(['cancel'=>$cancel]);





                    $trl = $model->UpdateStatus($map,3,$content,$_SESSION['onethink_admin']['user_auth']['uid']);
                    

                }elseif($type=='dakuan'){ //打款
                    /*
                     *    查看额度够不够
                     */
                    $map = array();
                    $map['status']  = 4;
                    $map['id']      = $id;


                    //商户付款流水号,唯一标识，不可重复
                    $no_order =date("YmdHis",time()).rand(100000,999999);
                    $is_order_num=D('Loan')->where('id='.$id)->find();
                    if($is_order_num['order_num']!=0){ //如果该用户的该流水号已存在,则不需要再次更换流水号
                       $no_order= $is_order_num['order_num'];
                    }else{
                        D('Loan')->where("id=$id")->save(['order_num'=>$no_order]);
                    }
                    // echo  $no_order;die;
                    
                    
                    //商户时间 ，商户提交订单时间
                    $dt_order = date("YmdHis",time());
                    //金额
                    $money_order =$payable;
                    //收款人姓名
                    $acct_name = $name;
                    //银行账号
                    $card_no =$card_number;
                    //订单描述
                    $info_order = '实时代付';
                    //对私标记
                    $flag_card = '0';
                    //服务器异步通知地址(打款成功之后通知的地址)
                    $notify_url = 'http://weixin.jcsmkj.cn/index.php?m=admin&c=notify&a=notify';

                    $r=$this->payment($no_order,$dt_order,$money_order,$acct_name,$card_no,$info_order,$flag_card,$notify_url);


                    ob_clean();
                    $r=json_decode($r,true);


                    if(!empty($r['oid_paybill'])){
                        $oid_paybill=$r['oid_paybill']; //支付单号 
                        $model->where("id=$id")->save(['oid_paybill'=>$oid_paybill]);
                    }
                    if(!empty($r['confirm_code'])){
                        // print_r($r['confirm_code']);
                        $code=$r['confirm_code'];   //校验码
                        $model->where("id=$id")->save(['code'=>$code]);

                    }
                    
                    if($r['ret_code']=='0000'){ //申请成功
                         $trl['status']=true;
                         $data=array(
                            'uid'=>$v_a['uid'],
                            'time'=>time(),
                            'text'=>'打款操作',
                            'maker'=>$_SESSION['onethink_admin']['user_auth']['uid'],//系统操作
                            );
                        D('LoanDefault')->add($data);
                        // $loan_time   =time();  
                        // //存入借款时间和到期时间、打款的银行卡号
                        // $loan_time   =time(); 
                        // $model->where("id=$id")->save(['loan_time'=>$loan_time,'bank_card'=>$card_no]);
                        // $trl    = $model->UpdateStatus($map,5,$content);

                        // $one=D('Loan')->where('id='.$id)->find(); 
                        // $bank=D('BankCard')->where('uid='.$one['uid'])->find(); 
                        // $date=date("Y年m月d日",$one['expire_time']);                                                                                                
                        // $url='http://sh2.ipyy.com/sms.aspx?action=send&userid=&account=jkwl362&password=ndp987&mobile='.$bank['mobile'].'&content=【西西钱包】'.$bank['name'].'您好！您申请的借款已由资金方汇款成功，到账金额'.$one['payable'].'元，合同到期为'.$date.'，合同金额为'.$one['repayment'].'元，客服热线0771-5717965&sendTime=&extno=';
                    
                        // $this->send_post($url);

                    }else{
                        $trl=['info'=>$r['ret_msg'],'status'=>false];
                    }
                }elseif($type=='hai'){ //还款
                    /*
                     *    查看额度够不够
                     */
                    $map = array();
                    $map['status']  = 5;
                    $map['id']      = $id;
                    $one=D('Loan')->where('id='.$id)->find();
                    if($one['repay_method']==1){
                        $method='银行卡';
                    }else if($one['repay_method']==2){
                        $method='支付宝';
                    }else{
                        $method='其他方式';
                    }
                   

                    $this->send_post($url);
                    $trl = $model->UpdateStatus($map,6,$content,$_SESSION['onethink_admin']['user_auth']['uid']);
                     $bank=D('BankCard')->where('uid='.$one['uid'])->find();

                    $url='http://sh2.ipyy.com/sms.aspx?action=send&userid=&account=jkwl362&password=ndp987&mobile='.$bank['mobile'].'&content=【西西钱包】'.$bank['name'].'您好！您已通过'.$method.'主动还款，已为您恢复额度，可继续使用，客服热线0771-5717965&sendTime=&extno=';
                     // print_r($url);die;

                    

                }

                if($trl['status']==true){
                    // echo json_encode(array('status'=>1,'info'=>'操作成功','url'=>U('index')));die;
                    ob_clean();
                    $this->AjaxReturn(array('status'=>1,'info'=>'操作成功','url'=>U('capital/index')));
                }else{
                    ob_clean();
                    $rtl['status']=0;
                    $this->AjaxReturn($trl);
                }
            
            
        }else{
                $id         = I('get.id');
                $type       = I('get.type');
                if($type=='pass'){  //通过
                    $map = array();
                    $map['status']  = 2;
                    $map['id']      = $id;
                    $uid=$_SESSION['onethink_admin']['user_auth']['uid'];
                    $trl = $model->UpdateStatus($map,4,'',$uid);

                    // 记录通过的时间  一个小时有效  多加2分钟时间
                    D('Timeout')->add(['uid'=>$uid,'time'=>(time()+3720)]);
                    if(!empty($trl)){
                        // 短信通知
                        $one=D('Loan')->where('id='.$id)->find();
                        $bank=D('BankCard')->where('uid='.$one['uid'])->find();
                        $num=substr($bank['card_number'], -4);
                        $url='http://sh2.ipyy.com/sms.aspx?action=send&userid=&account=jkwl362&password=ndp987&mobile='.$bank['mobile'].'&content=【西西钱包】'.$bank['name'].'您好！很开心的通知您、您申请的借款'.$one['money'].'元已通过审核，将在2小时内由资金方汇入您的('.$num.')账户,客服热线0771-5717965&sendTime=&extno=';
                        $this->send_post($url);
                         ob_clean();
                         $this->AjaxReturn(array('status'=>1,'info'=>'操作成功','url'=>U('capital/index')));
                    }else{
                        ob_clean();
                        $this->AjaxReturn(array('status'=>0,'info'=>'操作失败'));
                    }
                }else{
                    ob_clean();
                    $this->AjaxReturn(array('status'=>2,'info'=>'非法操作'));
                }

            
        }
    }



    public function get_code(){
        if(IS_POST){
            $type=I('post.type');
            $ht=I('post.ht');

            for($i=0;$i<6;$i++){
                $code.=rand(1,9);
            }
            $uid=$_SESSION['onethink_admin']['user_auth']['uid'];
            $mobile=D('Ucenter_member')->where('id='.$uid)->find();
            $mobile=$mobile['mobile'];

            $num=substr($mobile, 0,3)."***".substr($mobile, -4);
            if($type==1){
                $url='http://sh2.ipyy.com/sms.aspx?action=send&userid=&account=jkwl362&password=ndp987&mobile='.$mobile.'&content=【西西管理中心】正在操作'.$ht.'该笔订单通过审核，验证码是'.$code.'&sendTime=&extno=';
            }else if($type==5){
                $url='http://sh2.ipyy.com/sms.aspx?action=send&userid=&account=jkwl362&password=ndp987&mobile='.$mobile.'&content=【西西管理中心】正在操作'.$ht.'该笔订单不通过审核，验证码是'.$code.'&sendTime=&extno=';
            }else if($type==6){
                $url='http://sh2.ipyy.com/sms.aspx?action=send&userid=&account=jkwl362&password=ndp987&mobile='.$mobile.'&content=【西西管理中心】账号'.$num.'正在确认付款订单，该笔订单合同号'.$ht.'，验证码是'.$code.'，请核实好在进行付款确认，一切后果确认付款人承担，&sendTime=&extno=';

            }
            $this->send_post($url);
            print_r($code);die;
            // print_r('短信已发送，请注意查收');
        }   
    }



    public function config(){
        //获取列表数据
        $map =array();
        $list   =   $this->lists('LoanConfig', $map);
        $this->assign('_list', $list);
        $this->meta_title = '借款配置';

        $this->display();
    }
    public function configadd(){
        if(IS_POST){
            $nickname        = I('post.nickname');
            $price           = I('post.price');
            $days_qin        = I('post.days_qin');
            $vetting1_qin    = I('post.vetting1_qin');
            $accrual_qin     = I('post.accrual_qin');
            $manag_qin       = I('post.manag_qin');
            $days_shi        = I('post.days_shi');
            $vetting1_shi    = I('post.vetting1_shi');
            $accrual_shi     = I('post.accrual_shi');
            $manag_shi       = I('post.manag_shi');
            $status          = I('post.status');
            $data = [
                'nickname'      =>$nickname,
                'price'         =>$price,
                'days_qin'      =>$days_qin,
                'vetting1_qin'  =>$vetting1_qin,
                'accrual_qin'   =>$accrual_qin,
                'manag_qin'     =>$manag_qin,
                'days_shi'      =>$days_shi,
                'vetting1_shi'  =>$vetting1_shi,
                'accrual_shi'   =>$accrual_shi,
                'manag_shi'     =>$manag_shi,
                'status'        =>$status,
            ];
            $model = M('LoanConfig');
            if($model->create($data)){
                $model->add($data);
                $this->success('添加成功！',U('config'));
            }else{
                $this->error('添加失败！');
            }
        }else{
            $this->meta_title = '添加';
            $this->display('configedit');
        }
    }
    /**
     *  添加
     * @author huajie <banhuajie@163.com>
     */
    public function configedit($id = 0){
        if(IS_POST){
            $id              = I('post.id');
            $nickname        = I('post.nickname');
            $price           = I('post.price');
            $days_qin        = I('post.days_qin');
            $vetting1_qin    = I('post.vetting1_qin');
            $accrual_qin     = I('post.accrual_qin');
            $manag_qin       = I('post.manag_qin');
            $days_shi        = I('post.days_shi');
            $vetting1_shi    = I('post.vetting1_shi');
            $accrual_shi     = I('post.accrual_shi');
            $manag_shi       = I('post.manag_shi');
            $status          = I('post.status');
            $data = [
                'nickname'      =>$nickname,
                'price'         =>$price,
                'days_qin'      =>$days_qin,
                'vetting1_qin'  =>$vetting1_qin,
                'accrual_qin'   =>$accrual_qin,
                'manag_qin'     =>$manag_qin,
                'days_shi'      =>$days_shi,
                'vetting1_shi'  =>$vetting1_shi,
                'accrual_shi'   =>$accrual_shi,
                'manag_shi'     =>$manag_shi,
                'status'        =>$status,
            ];
            $model = M('LoanConfig');
            if($model->create($data)){
                $model->where('id='.$id)->save($data);
                $this->success('修改成功！',U('config'));
            }else{
                $this->error('修改失败！');
            }
        }else{
            empty($id) && $this->error('参数错误！');
            $info = M('LoanConfig')->field(true)->find($id);
            $this->assign('info', $info);
            $this->meta_title = '修改';
            $this->display();
        }
    }


    function payment($no_order,$dt_order,$money_order,$acct_name,$card_no,$info_order,$flag_card,$notify_url){
        return Payment($no_order,$dt_order,$money_order,$acct_name,$card_no,$info_order,$flag_card,$notify_url);
    }

    function query_payment($order_num,$oid_paybill){
        return Querypayment($order_num,$oid_paybill);
    }
    // 确认订单
    function confirm_payment(){
        //服务器异步通知地址(打款成功之后通知的地址)
        $notify_url = 'http://weixin.jcsmkj.cn/index.php?m=admin&c=notify&a=notify';
        $id=I('post.id');
        $card_no=I('post.card'); 
        //根据id查出流水号和验证码
        $info=D('Loan')->where("id=$id")->find();  
        $no_order=$info['order_num'];
        $confirm_code=$info['code'];

        //调用确认订单接口
        $r_confirm=Confirm_payment($no_order,$confirm_code ,$notify_url);
        $r_confirm=json_decode($r_confirm,true);

        if(!empty($r_confirm['oid_paybill'])){  //保存成功后返回的订单号
            $oid_paybill=$r_confirm['oid_paybill']; //支付单号 
            $model->where("id=$id")->save(['oid_paybill'=>$oid_paybill]);
        }

        if($r_confirm['ret_code']=='0000'){ //确认申请成功之后，修改数据库（支付平台处理快，2分钟内可支付）
            // $trl = $model->UpdateStatus($map,5,$content); 
            $loan_time   =time();
               
            //存入借款时间和到期时间、打款的银行卡号
            $model->where("id=$id")->save(['loan_time'=>$loan_time,'bank_card'=>$card_no]);
            $map = array();
            $map['status']  = 4;
            $map['id']      = $id;
            $trl    = $model->UpdateStatus($map,5,$content,$_SESSION['onethink_admin']['user_auth']['uid']);
            $one=D('Loan')->where('id='.$id)->find(); 
            $bank=D('BankCard')->where('uid='.$one['uid'])->find(); 
            $date=date("Y年m月d日",$one['expire_time']);                                                                                                
            $url='http://sh2.ipyy.com/sms.aspx?action=send&userid=&account=jkwl362&password=ndp987&mobile='.$bank['mobile'].'&content=【西西钱包】'.$bank['name'].'您好！您申请的借款已由资金方汇款成功，到账金额'.$one['payable'].'元，合同到期为'.$date.'，合同金额为'.$one['repayment'].'元，客服热线0771-5717965&sendTime=&extno=';
        
            $this->send_post($url);
                
        }else{
            $trl=['status'=>false];
        }
        if($trl['status']==true){
            ob_clean();
            $this->AjaxReturn(array('status'=>1,'info'=>'操作成功','url'=>U('capital/index')));
        }else{
            ob_clean();
            $this->AjaxReturn(array('status'=>0,'info'=>'操作失败'));
        }

    }

    function orderquery($id){
        $one=D('Loan')->where('id='.$id)->find();
        // print_r($one);die;
        $re=Orderquery($one['pay_num'],$one['dt_order']);
        $re=json_decode($re,true);
        if($re['ret_code']=='0000'){

             if($re['result_pay']=='APPLY'){  //返回的结果
                
                ob_clean();
                $this->AjaxReturn(array('info'=>'交易申请中'));

            }else if($re['result_pay']=='CHECK'){
                ob_clean();
                $this->AjaxReturn(array('info'=>'交易复核申请中'));
            }else if($re['result_pay']=='SUCCESS'){
                D('Loan')->where('id='.$id)->save(['oid_returnbill'=>$re['oid_paybill']]);
                ob_clean();
                $this->AjaxReturn(array('info'=>'交易已完成'));
            }else if($re['result_pay']=='PROCESSING'){
               ob_clean();
                $this->AjaxReturn(array('info'=>'交易处理中'));
            }else if($re['result_pay']=='CANCEL'){
                ob_clean();
                $this->AjaxReturn(array('info'=>'付款退款'));
            }else if($re['result_pay']=='FAILURE'){
                ob_clean();
                $this->AjaxReturn(array('info'=>'交易失败'));
            }else if($re['result_pay']=='CLOSED'){
                ob_clean();
                $this->AjaxReturn(array('info'=>'交易已关闭'));
            }

            // APPLY 付款申请
            // CHECK 复核申请
            // SUCCESS 付款成功
            // PROCESSING 付款处理中
            // CANCEL 付款退款（付款成
            // 功后，有可能发生退款）
            // FAILURE 付款失败
            // CLOSED 付款关闭  result_pay  info_order
        }else{
            ob_clean();
            $this->AjaxReturn(array('info'=>$re['ret_msg']));
        }
        
    }




    // 短信的发送人和密码
    function get_dx(){
        $data['account']='jkwl362';
        $data['password'] ='ndp987';
        ob_clean();
        $this->AjaxReturn($data);


    }

    // /**
    //  * 发送post请求
    //  * @param string $url 请求地址
    //  * @param array $post_data post键值对数据
    //  * @return string
    //  */
    function send_post($url) {
        $post_data = array(
          'username' => 'jkwl362',
          'password' => 'ndp987'
        );
     
      $postdata = http_build_query($post_data);
      $options = array(
        'http' => array(
          'method' => 'POST',
          'header' => 'Content-type:application/x-www-form-urlencoded',
          'content' => $postdata,
          'timeout' => 60 // 超时时间（单位:s）
        )
      );
      $context = stream_context_create($options);
      $result = file_get_contents($url, false, $context);
    }   



    // 一键扣款
    public function kouk(){
        $ids=I('post.ids');
        $ht=[];
        $error=[];
        $success=0;
        $default=0;
        foreach ($ids as $key => $v) {
            $one=D('Loan')->where("id=$v")->find();
            // 发起扣款
            $re=$this->agreenoauthapply($v);
            // print_r($re);die;
            // $re=json_decode($re,true);
            if($re['ret_code']=='0000'){
                $success++;
            }else{
                $default++;
                $ht[]=$one['id'];
                $error[]=$re['ret_msg'];
            }
        }
        // echo json_encode(array('count'=>count($ids),'success'=>$success,'default'=>$default,'ht'=>$ht,'error'=>$error));die;
        
        
        print_r("提交扣款人数：".count($ids)."，成功：".$success."，失败：".$default."。失败合同号：");
        print_r($ht);
        print_r("对应失败原因：");
        print_r($error);
        die;




    } 

    //授权申请API  $card_number,$money_order,$acct_name,$oid_paybill
     function agreenoauthapply($id){
        // $type=I('post.type');
        // $id=I('post.id');
        $is_set=D('Loan')->where("id=$id")->find();

      
        $uid=$is_set['uid']; 
        $card_number=$is_set['bank_card'];
        //银行卡号一定要对应，因为一个用户可以绑定多张银行卡
        $yinhang=D('BankCard')->where(array('uid'=>$uid,'card_number'=>$card_number))->find();
    
        $no_agree=$yinhang['no_agree'];
        
        $repayment_no =date("YmdHis",time()).rand(100000,999999);
        
        if($is_set['repayment_no']!=0){ //如果该用户的该还款计划编号已存在,则不需要再次更换还款计划编号
           $repayment_no= $is_set['repayment_no'];
        }else{
            D('Loan')->where('id='.$id)->save(['repayment_no'=>$repayment_no]);
        }
        $date=time();//计划还款日期
        $yq_day=(strtotime(date("Y-m-d"))-strtotime(date("Y-m-d",$is_set['expire_time'])))/86400; //逾期天数计算

        if($yq_day>0){
            $money=$is_set['repayment']+0.02*$is_set['repayment']*$yq_day; //逾期后还款，不延期
        }else{
            $money=$is_set['repayment'];   //未逾期
        }
        $r=Agreenoauthapply($uid,$no_agree,$date,$money,$repayment_no); 
        // return $r;
        $r=json_decode($r,true);
         // print_r($r);die;
        
        if($r['ret_code']=='0000'){
            $re=$this->bankcardrepayment($id,$date,$money);
            $re=json_decode($re,true);
            if($re['ret_code']=='0000'){
               return $re;
            }else{
               return $r;
            }
            
        }else{
           return $r;
        }
    }
// 扣款还款申请
    function bankcardrepayment($id,$date,$money){
        // $id         =201709156838361504;
        $is_set     =D('Loan')->where("id=$id")->find();
        $uid        =$is_set['uid']; 
        $card_number=$is_set['bank_card'];
        //银行卡号一定要对应，因为一个用户可以绑定多张银行卡
        $yinhang=D('BankCard')->where(array('uid'=>$uid,'card_number'=>$card_number))->find();
        
        $no_agree=$yinhang['no_agree'];
        $pay_num=date("YmdHis",time()).rand(100000,999999);
        if($is_set['pay_num']!=0){ //如果该用户的该商户系统订单号已存在,则不需要再次更换商户系统订单号
           $pay_num= $is_set['pay_num'];
        }else{
            D('Loan')->where('id='.$id)->save(['pay_num'=>$pay_num]);
        }
        $repayment      =$money;
        $expire_time    =$date;
        $repayment_no   =$is_set['repayment_no'];

        
        $name       =$is_set['name'];
        $real       =D('realname')->where("uid=".$uid)->find();
        $id_no      =$real['identityNo'] ;//身份证号
        $no_order   =$yinhang['no_order'];
        $bind_mob   =$yinhang['mobile'];
        $res        = D('member')->where('uid='.$uid)->find();
        $reg_time   = $res['reg_time'];
        $dt_order   =date("YmdHis",time());  //存下订单时间 查询时需要使用
        D('Loan')->where('id='.$id)->save(['dt_order'=>$dt_order]);
        
                           //$uid,$no_agree,$pay_num,$repayment,$expire_time,$repayment_no,$name,$id_no,$no_order,$bind_mob,$reg_time 
        $r=Bankcardrepayment($uid,$no_agree,$pay_num,$repayment,$expire_time,$repayment_no,$name,$id_no,$no_order,$bind_mob,$reg_time,$dt_order);
        return $r;

    }



// 修改借款金额
    public function change_money(){
        $ht=I('post.ht');
        $money=I('post.money');
        $one=D('Loan')->where("id=".$ht)->find();

        $data['vetting1']=$one['vetting1']/$one['money']*$money;
        $data['accrual']=$one['accrual']/$one['money']*$money;
        $data['manag']=$one['manag']/$one['money']*$money;
        $data['money']=$money;
        $data['repayment']=$money;

        $data['payable']=$money-$data['vetting1']-$data['accrual']-$data['manag'];

        $trl=D('Loan')->where("id=".$ht)->save($data);
        if($trl==1){
            print_r('借款金额修改成功');
        }
        die;
    }
// 修改还款金额
    public function change_repayment(){
        $ht=I('post.ht');
        $repayment=I('post.repayment');

        $trl=D('Loan')->where("id=".$ht)->save(['repayment'=>$repayment]);
        if($trl==1){
            print_r('还款金额修改成功');
        }
        die;
    }
// 修改应付金额
    public function change_payable(){
        $ht=I('post.ht');
        $payable=I('post.payable');

        $trl=D('Loan')->where("id=".$ht)->save(['payable'=>$payable]);
        if($trl==1){
            print_r('应付金额修改成功');
        }
        die;
    }
// 修改到期时间
    public function change_expire_time(){
        $ht=I('post.ht');
        $expire_time=I('post.expire_time');
        $expire_time=strtotime($expire_time);
        // print_r($expire_time);die;
        $trl=D('Loan')->where("id=".$ht)->save(['expire_time'=>$expire_time]);
        if($trl==1){
            print_r('还款时间修改成功');
        }
        die;
    }





}
